package ano.it.controller;

import ano.it.constant.MessageConstant;
import ano.it.entity.PageResult;
import ano.it.entity.QueryPageBean;
import ano.it.entity.Result;
import ano.it.pojo.Device;
import ano.it.service.UserService;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;
    @Reference
    private UserService userService;
    @RequestMapping("/getUsername")
    public Result getUsername(){
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if(user!=null){
            return new Result(true, MessageConstant.GET_USERNAME_SUCCESS,user.getUsername());
        }
        return new Result(false,MessageConstant.GET_USERNAME_FAIL);
    }
    @RequestMapping("/addPermission")
    public Result addPermission(Integer userId,Integer roleIds[]){
        try {
            userService.addPermission(roleIds,userId);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.ADD_POWER_FAIL);
        }
        return new Result(false,MessageConstant.ADD_POWER_SUCCESS);

    }
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
        PageResult pageResult=userService.findPage(queryPageBean);
        return pageResult;
    }
    @RequestMapping("/add")
    public Result add(@RequestBody ano.it.pojo.User user){
        try {
            user.setPassword(passwordEncoder.encode(user.getPassword()));
            userService.add(user);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.ADD_DEVICE_FAIL);
        }
        return new Result(true,MessageConstant.ADD_DEVICE_SUCCESS);
    }
}
